/*
    // 使用 koa 搭建出来一个后端支付的接口 
*/

const Koa = require('koa');
const app = new Koa();

const router = require("koa-router")();

// 引入阿里云下的 sdk
const AlipaySdk = require("alipay-sdk").default;
const AlipayFormData = require("alipay-sdk/lib/form").default;

// 创建sdk
const alipaySdk = new AlipaySdk({
    appId:"2021000121677272",// 支付宝开发平台 沙箱生成 appId
    signType:"RSA2", // 签名算法 默认RSA2
    // 支付宝密钥
    privateKey:"MIIEogIBAAKCAQEAlur1uh9uIs17tTtvGfJjf9tWqu4PEKXffN9GRDdTxpidTJuT/BagV1m7nfupLZVwsvvBBZPVUgiJDuFTVYT1qFGqspVl3cm3KchF/muQuvwwFlGLPUF5DjCl/C1M/gmLAE19q/qI8QKc0MBunrcW31836HZu4M1x+CsgNy3sS7ktIMmVytKA8TDLPHArgr0uGNEIqLBiIsTfrDrMfB1QO7LvmzKj9N2pZEr9LN8/YWZwDn8fepxyKpU1ImNGCxzAVj7rangS7d1OJhb3GRoKQ7banuG6OLFygMEI0BzjvRtEKKcPSku4QCWs+et9/V4PX5OVFl3R4LlSgNtLqeAWZwIDAQABAoIBAFBRpguzdIsjLyaKBhwaC2hdlKeN4QisLuAneB8QDw8P5A+EcWLlq9oxUI/JAwXWlc87+0N7pTluf3si4pYOGCvHowA+UKOUGl4rT00TdEh/tRv7tA4azVGHBJ/MgEBnVcoIc8zWnpEeIdVbxMPFj2+8HmYiuen8jR5V3WRglXTKvDkoenEzZMDOQcnhPkJZuMQxWAMH0aL293RF227L0N66tOejXLtosR2vOpoSKAS53zAJbMHz/2lZJanYy+zcv5k3zq4Z5grbOmHY0Y1UxrhWSScDNywEjnLpQmteZ/vXQBrweyKvBYBGylMopLLu2odTMddTBXNmGEbTAhgJK9ECgYEAz4oiwVgzNk0MiT6QFSFs3IE/wFxxmXBYhjyslwqdc4wltlxqoMkR4VrqlY/2Hg8q3ueUKK+i1DY3Sk7HEhCVyH2xjQV4F7EJ+u3kXdr9AUgPuii1m/azyjfP0SgnoO6xATuge9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7banuG6OLFygMEI0BzjvRtEKKcPSku4QCWs+et9/V4PX5OVFl3R4LlSgNtLqeAWZwIDAQAB",
    gateway:"https://openapi.alipay.com/gateway.do" // 支付宝网关地址
})

router.get("/pay",async ctx =>{
    const formData = new AlipayFormData()
    formData.setMethod("get")
    formData.addField("notifyUrl","https://www.baidu.com")
    formData.addField("biz_Content",{
        out_trade_no:"xxxxx1",// 商品订单号 通过 base64 转换 可以包含字母、数字
        product_code:"FAST_INSTANT_TRADE_PAY",// 销售产品码
        total_amount:"10000",// 订单金额 单位为元
        subject:"2004A", // 订单标题
        body:"2004A详情" // 订单详情
    })
    formData.addField("returnUrl","http://localhost:7001/");
    
    const result = await alipaySdk.exec(
        // result 代表可以支付链接url
        "alipay.trade.page.pay",//统一下单支付页面
        {},// api请求的参数
        {formData:formData}
    ) 
    
    ctx.body = {
        code:1,
        result
    }
})

app.use(router.routes(),router.allowedMethods())
app.listen("9000",()=>{
    console.log("service is running at 9000");
})